<template>
  <div class="app-container">
    <ResizeBox :treeData="objectOptions" @pitchOnData="pitchOnData">
      <template>
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="80px"
        >
          <el-form-item label="单元名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入单元名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="部门" style="width: 60px" />
          <el-form-item label="" prop="deptId" style="width: 220px">
            <treeselect
              v-model="queryParams.deptId"
              :options="deptOptions"
              :show-count="true"
              placeholder="请选择归属部门"
            />
          </el-form-item>
          <el-form-item label="负责人" prop="userId">
            <UserSelect
              :userId="queryParams.userId"
              selectType="userName"
              @upData="
                (val) => {
                  queryParams.userId = val;
                }
              "
              remote
              reserveKeyword
              placeholder="请选择负责人"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['syf:unit:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['syf:unit:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['syf:unit:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="unitList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="安全风险对象"
            align="center"
            prop="objectName"
          />
          <el-table-column label="单元名称" align="center" prop="name" />
          <el-table-column label="部门" align="center" prop="deptName" />
          <el-table-column label="负责人" align="center" prop="userName" />
          <el-table-column
            label="扫码排查"
            align="center"
            prop="scan"
            width="150"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.scan"
                @change="handleScanChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="停工状态"
            align="center"
            prop="status"
            width="150"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['syf:unit:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['syf:unit:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
    </ResizeBox>

    <!-- 添加或修改安全分析单元对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全风险对象" prop="objectId">
              <el-select
                v-model="form.objectId"
                filterable
                placeholder="请选择安全风险对象"
                style="width: 100%"
              >
                <el-option
                  v-for="item in objectOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单元名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入单元名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="userId">
              <UserSelect
                :userId="form.userId"
                :deptId="form.deptId"
                @upData="
                  (val) => {
                    form.userId = val;
                  }
                "
                placeholder="请选择负责人"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="详细位置" prop="detailLocation">
              <el-input
                v-model="form.detailLocation"
                placeholder="请输入详细位置"
              />
              <el-button
                type="text"
                icon="el-icon-map-location"
                @click="handleUpdate(scope.row)"
                >所属区域</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="默认IMEI号" prop="imei">
              <el-input v-model="form.imei" placeholder="请输入默认IMEI号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="scan" label="扫码排查:">
              <el-switch v-model="form.scan"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import {
  listUnit,
  getUnit,
  delUnit,
  addUnit,
  updateUnit,
  upUnitStatus,
} from "@/api/syf/risk/unit";
import { listObject } from "@/api/syf/risk/object";
import ResizeBox from "@/components/syf/ResizeBox/index";
import UserSelect from "@/components/syf/UserSelect/index";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Unit",
  components: { Treeselect, ResizeBox, UserSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安全风险对象树选项
      objectOptions: undefined,
      // 安全分析单元表格数据
      unitList: [],
      // 部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        objectId: null,
        name: null,
        deptId: null,
        userId: null,
        objectIds: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        objectId: [
          { required: true, message: "安全风险对象不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "单元名称不能为空", trigger: "blur" },
        ],
        deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        userId: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        detailLocation:[
          { required: true, message: "详细位置不能为空", trigger: "blur" },
        ],
        imei: [
            {
              validator: (rule, value, callback) => {
                const pattern = /^[\d]{15}(?:[\d]{2})?$/;
                if (value != null && value != '' && !pattern.test(value)) {
                  callback(new Error('请输入正确的IMEI码'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
      },
    };
  },
  created() {
    this.getObject();
    this.getDeptTree();
    this.getList();
  },
  methods: {
    /** 查询安全风险对象树 */
    getObject() {
      listObject().then((res) => {
        let tree = [];
        res.rows.forEach((element) => {
          tree.push({
            id: element.id,
            name: element.name,
          });
        });
        this.objectOptions = tree;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询安全分析单元列表 */
    getList() {
      this.loading = true;
      listUnit(this.queryParams).then((response) => {
        this.unitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        objectId: null,
        name: null,
        detailLocation: null,
        status: null,
        imei: null,
        lonLat: null,
        scan: null,
        deptId: null,
        userId: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        firmId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.status = true;
      this.title = "添加安全分析单元";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUnit(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改安全分析单元";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUnit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUnit(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除安全分析单元编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUnit(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "syf/unit/export",
        {
          ...this.queryParams,
        },
        `unit_${new Date().getTime()}.xlsx`
      );
    },
    //选中树节点
    pitchOnData(val) {
      let objectIds = [];
      val.forEach((item) => {
        objectIds.push(item.id);
      });
      this.queryParams.objectIds = objectIds;
      this.handleQuery();
    },
    //扫码排查开关
    handleScanChange(row) {},
    //修改状态
    handleStatusChange(row) {
      if (!row.status) {
        this.$prompt("请输入停工原因", "停工", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }).then(({ value }) => {
          upUnitStatus(row.id, value).then((res) => {
            this.$message({
              message: "停用安全分析单元成功！",
              type: "success",
            });
          });
        });
      } else {
        upUnitStatus(row.id, null).then((res) => {
          if (res.data.data) {
            this.$message({
              message: "启用安全分析单元成功！",
              type: "success",
            });
          }
        });
      }
    },
  },
};
</script>
